# -*- coding: utf-8 -*-
# @Author: Lemongman

import atexit
import sqlite3
from utils.loghandler import logger
from utils.globalVar import GLV


# sqlite数据库方法封装
class SQLite:
    conn = 'conn'
    GLV[conn] = False

    def __init__(self, dbFile):
        self.conn = self.connect(dbFile)

    @staticmethod
    def connect(dbFile):
        try:
            logger.info('链接sqlite：{}'.format(dbFile))
            conn = sqlite3.connect(dbFile)
            GLV[SQLite.conn] = conn
            return conn
        except Exception:
            logger.error('连接sqlite失败')
            return False

    def execute(self, sqlStr, op=1, data=None):
        """
        执行sql语句
        :param sqlStr:
        :param op: 1执行 2查询
        :param data:
        :return:
        """
        cursor = self.conn.cursor()
        result = False
        try:
            if data is not None:
                if isinstance(data[0], list) or isinstance(data[0], tuple):
                    for x in data:
                        cursor.execute(sqlStr, x)
                else:
                    cursor.execute(sqlStr, data)
                result = True
            else:
                result = cursor.execute(sqlStr)
            if op == 2:
                result = cursor.fetchall()
        except Exception as e:
            logger.error('执行sql语句失败')
            logger.error(e)
        cursor.close()
        self.conn.commit()
        return result

    @staticmethod
    @atexit.register
    def close():
        if GLV[SQLite.conn]:
            logger.info('关闭sqlite链接')
            GLV[SQLite.conn].close()


sqllite = SQLite(r'C:\Users\Lemon\Desktop\my.db')
